package com.udi.project.business.utils.generate;

import com.udi.project.business.utils.check.CheckCodeUtils;
import com.udi.project.business.utils.redis.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
/**
 * @author Admin
 * Di生成核心业务
 */
@Component
public class GenerateDi {

    @Autowired
    /**校验码生成*/
    private CheckCodeUtils checkCodeUtils;
    @Autowired
    private RedisUtils redisUtils;

    /**
     *
     * @Description:DI生成器
     * @param identifier 厂商识别代码
     * @param packageCode 包装标识符
     * @return: Integer DI码
     * @Date: 2021/8/6 16:50
     * 包装标识符(1位)+厂商识别码(4位)【前三位690为国际单位(3位)】+商品项目码(2~5位)+校验码(1位)
     */

    public StringBuffer GetDi(Integer identifier,Integer packageCode){
        StringBuffer diStringBuffer = new StringBuffer();
        StringBuffer ims = null;
        diStringBuffer.insert(0,packageCode);
        //diStringBuffer.append(internationality);
        diStringBuffer.append(identifier);
        Integer modelCode = GetProjectCode(identifier);
        if(modelCode == 0){
            return ims.append("500");
        }else {diStringBuffer.append(modelCode);}
        //diStringBuffer.append("0");
        //线程不安全
        BigInteger diCode = new BigInteger(diStringBuffer.toString());
        diStringBuffer.append(checkCodeUtils.CheckCode(diCode));
        //diStringBuffer.insert(0,packageCode);

        return diStringBuffer;
    }

    /**
     *
     * @Description:项目代码生成器
     * @param identifier 厂商识别代码
     * @return: java.lang.Integer
     * @Date: 2021/8/6 17:18
     * 暂时以生成5位随机数来作为项目代码
     *  派生到我的代码片
     * System.out.println((int)((Math.random()*9+1)*10000));
     * */
    public Integer GetProjectCode(Integer identifier){
        Map<String,Object> random = new HashMap<>();

        /** 根据厂商码位数动态生成初始值*/
        Object number = redisUtils.hmval("projectCode",Integer.toString(identifier));
        if(number == null){
            Integer value = 10;
            Integer va = 10 ;

            int bit = 10 -  Integer.toString(identifier).length();
            for(int i=0;i<bit;i++){
                va =  va  * 10;
            }
            random.put(Integer.toString(identifier),va);
            redisUtils.hmset("projectCode",random);
        }

        int i = (int) redisUtils.hmval("projectCode",Integer.toString(identifier));
        /** 项目代码回收机制：Object转换Integer出现异常 */
        /*List<Object> code = redisUtils.lGet("recycle",0,-1);
        if(code.size()!=0){
            for(Object co:code){
                Integer codes = (Integer) co;
                redisUtils.lRemove("recycle",-1,codes);
                return codes;
            }
        }*/
        int sout = i+1;
        random.put(Integer.toString(identifier),sout);
        redisUtils.hmset("projectCode",random);
        random.clear();
        return sout;
    }
}